<template>
	<!-- 添加商品 -->
	<view class="addShop-main">
		<view class="addShop-form">
			<uni-forms ref="baseForm" :modelValue="baseFormData">
				<uni-forms-item label="商品分类" required :label-width="110">
					<uni-data-select v-model="baseFormData.category_id" :localdata="categoryList" @change="getChange"></uni-data-select>
				</uni-forms-item>
				<!-- <view v-if="!baseFormData.artid"> -->
					<uni-forms-item label="药品名称" required :label-width="110">
						<uni-easyinput v-model="baseFormData.name" placeholder="请输入药品名称" :disabled="baseFormData.artid"/>
					</uni-forms-item>
					<uni-forms-item label="库存数量" required :label-width="110">
						<uni-easyinput v-model="baseFormData.total" placeholder="请输入库存数量" :disabled="baseFormData.artid" />
					</uni-forms-item>
					<uni-forms-item label="是否处方" required :label-width="110">
						<view style="display: flex; align-items: center; height: 100%">
							<uni-data-checkbox v-model="baseFormData.recipeType" :localdata="recipeTypeList" :disabled="baseFormData.artid"/>
						</view>
					</uni-forms-item>
					<uni-forms-item label="规格" required :label-width="110">
						<uni-easyinput v-model="baseFormData.spec" placeholder="请输入规格" :disabled="baseFormData.artid"/>
					</uni-forms-item>
					<uni-forms-item label="单位" required :label-width="110">
						<uni-easyinput v-model="baseFormData.unit" placeholder="请输入单位" :disabled="baseFormData.artid"/>
					</uni-forms-item>
					<uni-forms-item label="商品条形码" required :label-width="110">
						<uni-easyinput v-model="baseFormData.barcode" placeholder="请输入商品条形码" :disabled="baseFormData.artid"/>
					</uni-forms-item>
					<uni-forms-item label="批准文号" required :label-width="110">
						<uni-easyinput v-model="baseFormData.fileno" placeholder="请输入批准文号" :disabled="baseFormData.artid"/>
					</uni-forms-item>
					<uni-forms-item label="有效日期" required :label-width="110">
						<view class="dateBox" @click="show = true" v-if="!baseFormData.artid">
							<text v-if="baseFormData.effective">{{ formatDate(baseFormData.effective) }}</text>
							<text v-else style="color: #999">请选择有效日期</text>
						</view>
						<view class="dateBox" v-else style="background-color: #F7F6F6;color: #d5d5d5;">
							{{ formatDate(baseFormData.effective) }}
						</view>
					</uni-forms-item>
					<uni-forms-item label="生产厂家" required :label-width="110">
						<uni-easyinput v-model="baseFormData.factory" placeholder="请输入生产厂家" :disabled="baseFormData.artid"/>
					</uni-forms-item>
					<uni-forms-item label="最低购买数量" required :label-width="110">
						<uni-easyinput v-model="baseFormData.small_num" placeholder="请输入最低购买数量" :disabled="baseFormData.artid"/>
					</uni-forms-item>
					<uni-forms-item label="用法" required :label-width="110">
						<uni-easyinput v-model="baseFormData.usages" placeholder="请输入用法" :disabled="baseFormData.artid" />
					</uni-forms-item>
					<uni-forms-item label="商品图片" required :label-width="110">
						<uni-file-picker limit="1" :auto-upload="true" v-model="imageList" fileMediatype="image" mode="grid" @select="select" @delete="delIMG"></uni-file-picker>
					</uni-forms-item>
					<uni-forms-item label="药剂类型" required :label-width="110">
						<uni-easyinput v-model="baseFormData.mediaName" placeholder="请输入药剂类型" :disabled="baseFormData.artid"/>
					</uni-forms-item>
				<!-- </view> -->
				
				<uni-forms-item label="价格" required :label-width="110">
					<view style="display: flex;align-items: center;">
						<text style="margin-right: 10rpx;">￥</text>
						<u-number-box step="0.25" decimal-length="2" v-model="baseFormData.price" :min="0.00" inputWidth="90"></u-number-box>
					</view>
				</uni-forms-item>
				
				<view class="shopInfo">商品详情</view>
				<editorComp ref="userInfoRef" :value="baseFormData.content" @input="getInput" keyName="content" />
			</uni-forms>
		</view>
		<view class="flashOpen-sub" @click="addShop" :style="bottomStyle">
			<view class="btn">{{ shopId ? '编辑商品' : '添加商品' }}</view>
		</view>
		
		<u-datetime-picker
			ref="datetimePicker"
			:show="show"
			v-model="baseFormData.effective"
			mode="date"
			@confirm="show = false"
			@close="false"
		></u-datetime-picker>
		
	</view>
</template>

<script>
import { flashManageAddGoods, flashManageCategory, flashManageDetail } from '../../../api/flashManage/index.js';
import editorComp from '../../../components/editorComp/editorComp.vue';
import { BASE_URL } from '../../../api/baseurl.js';
import { imageUrl } from '../../../utils/tools.js';
export default {
	data() {
		return {
			baseFormData: {
				name: '',
				total: '',
				recipeType: 0,
				spec: '',
				unit: '',
				barcode: '',
				fileno: '',
				effective: '',
				factory: '',
				small_num: '',
				usages: '',
				mediaName: '',
				price: '0.00',
				fileUrl: '',
				type: '',
				content: '',
				category_id: 0
			},
			show:false,
			// 是否处方
			recipeTypeList: [
				{
					text: '非处方药',
					value: 0
				},
				{
					text: '处方药',
					value: 1
				}
			],
			categoryList: [],
			storeType: '',
			imageList: [],
			tokenValue: '',
			shopId: ''
		};
	},
	async onLoad(option) {
		this.storeType = this.$store.state.storeType;
		const { id } = option;
		// 编辑or新增
		if (id) {
			this.shopId = id;
			uni.setNavigationBarTitle({
				title: '编辑商品'
			});
			this.getflashManageDetail(id);
		}

		await this.getcloudManageCategory();
		this.tokenValue = (await uni.getStorageSync('token')) || '';
	},

	components: {
		editorComp
	},

	computed: {
		bottomStyle() {
			const systemInfo = uni.getSystemInfoSync();
			const { safeAreaInsets } = systemInfo;
			const bottomSafeAreaHeight = safeAreaInsets.bottom || 0;
			return `padding-bottom: ${bottomSafeAreaHeight ? bottomSafeAreaHeight + 'px' : '20rpx'}`;
		}
	},

	methods: {
		addShop() {
			this.getflashManageAddGoods();
		},

		getChange(e) {
			this.baseFormData.category_id = e;
		},
		
		formatDate(dates) {
			if (!dates) {
				return '';
			}
			const date = new Date(dates);
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			return `${year}-${month}-${day}`;
		},

		// 获取商品详情
		async getflashManageDetail(id) {
			try {
				const resData = await flashManageDetail({
					id,
					type: this.storeType
				});
				this.baseFormData = resData.data;
				this.imageList = [
					{
						url: imageUrl(this.baseFormData.fileUrl),
						fullurl: this.baseFormData.fileUrl
					}
				];
			} catch (e) {
				throw Error(e);
			}
		},

		//图片上传
		select(e) {
			let filePath = e.tempFilePaths[0];
			uni.uploadFile({
				url: BASE_URL + 'common/upload',
				filePath: filePath,
				name: 'file',
				header: { token: this.tokenValue },
				success: (uploadFileRes) => {
					let path = JSON.parse(uploadFileRes.data);
					this.imageList.push({
						url: path.data.fullurl,
						fullurl: path.data.url
					});
				}
			});
		},

		//图片删除
		delIMG(e, type) {
			this.imageList = [];
		},

		// 商品分类
		async getcloudManageCategory() {
			try {
				const resData = await flashManageCategory({
					type: this.storeType
				});
				const list = resData.data;
				list.forEach((item) => {
					this.categoryList.push({
						value: item.id,
						text: item.name
					});
				});
			} catch (e) {
				throw Error(e);
			}
		},

		// 保存商品
		async getflashManageAddGoods() {
			this.baseFormData.effective = this.formatDate(this.baseFormData.effective);
			
			if(!this.baseFormData.name){
				return uni.showToast({
					title:'药品名称不能为空',
					icon:'none'
				})
			}
			
			if(!this.baseFormData.total){
				return uni.showToast({
					title:'库存数量不能为空',
					icon:'none'
				})
			}
			
			if(Number(this.baseFormData.total)<0){
				return uni.showToast({
					title:'库存数量必须大于0',
					icon:'none'
				})
			}
			
			if(!this.baseFormData.small_num){
				return uni.showToast({
					title:'最低购买数量不能为空',
					icon:'none'
				})
			}
			
			if(!this.baseFormData.price){
				return uni.showToast({
					title:'商品价格不能为空',
					icon:'none'
				})
			}
			let queryData = {};
			if (this.baseFormData.artid) {
				queryData = {
					id: this.shopId,
					type: this.storeType,
					category_id: this.baseFormData.category_id,
					content: this.baseFormData.content,
					price: this.baseFormData.price
				};
			} else {
				this.baseFormData.type = this.storeType;
				this.baseFormData.fileUrl = this.imageList[0].fullurl;
				queryData = this.baseFormData;
			}

			if (this.shopId) {
				this.baseFormData.id = this.shopId;
			}
			
			if(this.baseFormData.content){
				if(this.countImgTagsInRichText(this.baseFormData.content)>15){
					return uni.showToast({
						title:'商品详情图片不能超过15张',
						icon:'none'
					})
				}
			}
			
			try {
				const resData = await flashManageAddGoods(queryData);
				uni.showToast({
					title: `${this.shopId ? '编辑成功' : '添加成功'}`,
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack(-1);
				}, 500);
			} catch (e) {
				throw Error(e);
			}
		},

		getInput(e) {
			Object.assign(this.baseFormData, e);
		},
		
		countImgTagsInRichText(richText) {
		    const imgTagRegex = /<img\s+[^>]*>/gi;
		    return (richText.match(imgTagRegex) || []).length;
		}
	}
};
</script>

<style>
page {
	background-color: #fff;
}
</style>

<style scoped lang="scss">
.addShop-main {
	position: relative;
	.addShop-form {
		box-sizing: border-box;
		padding: 30rpx;
	}

	.flashOpen-sub {
		background-color: #fff;
		position: sticky;
		bottom: 0px;
		left: 0px;
		box-sizing: border-box;
		padding: 20rpx;
		width: 100%;
		padding-bottom: 0px;
		z-index: 9999;
		.btn {
			background-color: rgb(41, 121, 255);
			color: #fff;
			border: none;
			height: 90rpx;
			line-height: 90rpx;
			text-align: center;
			border-radius: 10rpx;
		}
	}
}

.shopInfo {
	text-align: center;
	font-size: 26rpx;
	margin: 40rpx 0px;
	color: #444;
}

.dateBox {
	height: 35px;
	border: 1px solid #dcdfe6;
	border-radius: 4px;
	color: #444;
	line-height: 35px;
	box-sizing: border-box;
	padding: 0px 10px;
}
</style>
